package weeek11.topic08;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.util.Collections;

/**
 * @author lfy
 */
public class RedisCounter {
    public static void main(String[] args) {
        String key = "test_counter";
        Long count;
        RedisCounter counter = new RedisCounter("127.0.0.1", 6379);
        count = counter.count(key);
        System.out.println("最初:"+count);
        counter.increase(key, 1);
        counter.increase(key, 2);
        count = counter.count(key);
        System.out.println("累加:"+count);

        counter.increase(key, -1);
        counter.increase(key, -1);
        counter.increase(key, -1);
        count = counter.count(key);
        System.out.println("累减:"+count);
    }

    private final JedisPool jedisPool;

    public RedisCounter(String host, int port) {
        jedisPool = new JedisPool(host, port);
    }

    /**
     * 增加
     *
     * @param key
     * @param count
     * @return
     */
    public void increase(String key, long count) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.incrBy(key, count);
        }
    }

    /**
     * 释放锁
     *
     * @param key
     * @return
     */
    public Long count(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            String s = jedis.get(key);
            if (s == null || s.length() == 0) {
                return null;
            }
            return Long.valueOf(s);
        }
    }
}